from nicegui import ui
import plotly.graph_objs as go

# 创建一个空的三维散点图，设置 mode 为 'lines+markers' 以显示点和连线
scatter_3d_fig = go.Figure(data=[go.Scatter3d(x=[0], y=[0], z=[0], mode='lines+markers')])

# 创建输入框和按钮
with ui.column():
    x_input_3d = ui.number(label='X 值', value=0)
    y_input_3d = ui.number(label='Y 值', value=0)
    z_input_3d = ui.number(label='Z 值', value=0)
    add_point_button_3d = ui.button('加入该点')
    delete_point_button_3d = ui.button('删除点')

# 创建 Plotly 三维图表，并放大尺寸
plot_3d = ui.plotly(scatter_3d_fig).classes('w-full h-120')  # 增加高度为 384px

# 定义添加点的按钮点击事件
def add_point_3d():
    x = x_input_3d.value
    y = y_input_3d.value
    z = z_input_3d.value

    # 更新现有的 Scatter3d 对象的 x、y 和 z 数据
    scatter_3d_fig.data[0].x = list(scatter_3d_fig.data[0].x) + [x]
    scatter_3d_fig.data[0].y = list(scatter_3d_fig.data[0].y) + [y]
    scatter_3d_fig.data[0].z = list(scatter_3d_fig.data[0].z) + [z]

    # 手动更新图表
    plot_3d.update()

# 定义删除点的按钮点击事件
def delete_point_3d():
    x = x_input_3d.value
    y = y_input_3d.value
    z = z_input_3d.value

    x_coords = list(scatter_3d_fig.data[0].x)
    y_coords = list(scatter_3d_fig.data[0].y)
    z_coords = list(scatter_3d_fig.data[0].z)

    try:
        index = x_coords.index(x)
        if y_coords[index] == y and z_coords[index] == z:
            # 删除该点
            del x_coords[index]
            del y_coords[index]
            del z_coords[index]

            scatter_3d_fig.data[0].x = x_coords
            scatter_3d_fig.data[0].y = y_coords
            scatter_3d_fig.data[0].z = z_coords

            # 手动更新图表
            plot_3d.update()
        else:
            ui.notify("点不存在", type="negative")
    except ValueError:
        ui.notify("点不存在", type="negative")

# 绑定添加点按钮点击事件
add_point_button_3d.on_click(add_point_3d)
# 绑定删除点按钮点击事件
delete_point_button_3d.on_click(delete_point_3d)

# 启动 NiceGUI 应用
ui.run(port=8087)